<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试详情 - 管理员</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .exam-info {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .exam-meta {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .meta-icon {
            font-size: 1.5em;
        }

        .meta-content {
            flex: 1;
        }

        .meta-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }

        .meta-value {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }

        .tabs {
            display: flex;
            background: white;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .tab {
            flex: 1;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            background: #f8f9fa;
            border: none;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .tab.active {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .tab-content {
            display: none;
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .tab-content.active {
            display: block;
        }

        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .btn-action {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: #212529;
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-action:hover {
            transform: translateY(-2px);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            border: 1px solid #e0e0e0;
        }

        .stat-icon {
            font-size: 2.5em;
            margin-bottom: 15px;
        }

        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #dc3545;
            margin-bottom: 10px;
        }

        .stat-label {
            color: #666;
            font-size: 1em;
        }

        .item-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .item-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            transition: all 0.3s ease;
        }

        .item-card:hover {
            border-color: #dc3545;
            transform: translateY(-2px);
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }

        .item-title {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
            margin: 0;
            flex: 1;
        }

        .item-meta {
            display: flex;
            flex-direction: column;
            gap: 5px;
            font-size: 0.9em;
            color: #666;
        }

        .item-content {
            color: #666;
            line-height: 1.5;
            margin-bottom: 15px;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .empty-description {
            font-size: 1em;
            line-height: 1.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #dc3545;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .table-container {
            overflow-x: auto;
            margin-top: 20px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .data-table th,
        .data-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 500;
        }

        .status-draft {
            background: #f8d7da;
            color: #721c24;
        }

        .status-published {
            background: #d4edda;
            color: #155724;
        }

        .status-ended {
            background: #cce5ff;
            color: #004085;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <span class="brand-icon">🎓</span>
                <span class="brand-text">学习平台</span>
            </div>
            <div class="nav-menu">
                <a href="dashboard.html" class="nav-link">
                    <span class="nav-icon">🏠</span>
                    <span class="nav-text">首页</span>
                </a>
                <a href="videos.html" class="nav-link">
                    <span class="nav-icon">📹</span>
                    <span class="nav-text">视频管理</span>
                </a>
                <a href="exam-management.html" class="nav-link active">
                    <span class="nav-icon">📝</span>
                    <span class="nav-text">考试管理</span>
                </a>
                <a href="users.html" class="nav-link">
                    <span class="nav-icon">👥</span>
                    <span class="nav-text">用户管理</span>
                </a>
            </div>
            <div class="nav-user">
                <span class="user-info" id="userInfo">加载中...</span>
                <button class="btn-logout" onclick="logout()">退出</button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <h1 class="page-title" id="examTitle">考试详情</h1>
            <p class="page-subtitle" id="examDescription">查看考试详细信息和管理</p>
        </div>

        <!-- 考试信息 -->
        <div class="exam-info">
            <div class="exam-meta">
                <div class="meta-item">
                    <div class="meta-icon">👨‍🏫</div>
                    <div class="meta-content">
                        <div class="meta-label">出题老师</div>
                        <div class="meta-value" id="teacherName">未知</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">📊</div>
                    <div class="meta-content">
                        <div class="meta-label">题目数量</div>
                        <div class="meta-value" id="questionCount">0 题</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">⏱️</div>
                    <div class="meta-content">
                        <div class="meta-label">考试时长</div>
                        <div class="meta-value" id="timeLimit">0 分钟</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">👥</div>
                    <div class="meta-content">
                        <div class="meta-label">参与学生</div>
                        <div class="meta-value" id="studentCount">0 人</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">📅</div>
                    <div class="meta-content">
                        <div class="meta-label">创建时间</div>
                        <div class="meta-value" id="createdTime">未知</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">📈</div>
                    <div class="meta-content">
                        <div class="meta-label">考试状态</div>
                        <div class="meta-value" id="examStatus">未知</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="stats-grid" id="statsGrid" style="display: none;">
            <div class="stat-card">
                <div class="stat-icon">👥</div>
                <div class="stat-number" id="totalParticipants">0</div>
                <div class="stat-label">总参与人数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">✅</div>
                <div class="stat-number" id="completedCount">0</div>
                <div class="stat-label">已完成人数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📊</div>
                <div class="stat-number" id="averageScore">0</div>
                <div class="stat-label">平均分数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🎯</div>
                <div class="stat-number" id="passRate">0%</div>
                <div class="stat-label">通过率</div>
            </div>
        </div>

        <!-- 标签页 -->
        <div class="tabs">
            <button class="tab active" onclick="switchTab('overview')">概览</button>
            <button class="tab" onclick="switchTab('questions')">题目管理</button>
            <button class="tab" onclick="switchTab('students')">学生管理</button>
            <button class="tab" onclick="switchTab('results')">考试结果</button>
        </div>

        <!-- 概览标签页 -->
        <div id="overviewTab" class="tab-content active">
            <div class="action-bar">
                <div>
                    <button class="btn-action btn-success" onclick="publishExam()" id="publishBtn" style="display: none;">
                        📢 发布考试
                    </button>
                    <button class="btn-action btn-warning" onclick="unpublishExam()" id="unpublishBtn" style="display: none;">
                        ⏸️ 取消发布
                    </button>
                    <button class="btn-action btn-danger" onclick="endExam()" id="endBtn" style="display: none;">
                        🏁 结束考试
                    </button>
                </div>
                <div>
                    <button class="btn-action btn-primary" onclick="viewExamResults()">
                        📊 查看详细结果
                    </button>
                </div>
            </div>

            <div class="exam-info">
                <h3>考试描述</h3>
                <p id="examDescriptionText">暂无描述</p>
            </div>
        </div>

        <!-- 题目管理标签页 -->
        <div id="questionsTab" class="tab-content">
            <div class="action-bar">
                <h3>考试题目</h3>
            </div>

            <div id="questionLoadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载题目列表...</p>
            </div>

            <div id="questionList" class="item-grid" style="display: none;">
                <!-- 题目列表将在这里动态生成 -->
            </div>

            <div id="questionEmptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">❓</div>
                <h3 class="empty-title">暂无题目</h3>
                <p class="empty-description">这个考试还没有添加任何题目</p>
            </div>
        </div>

        <!-- 学生管理标签页 -->
        <div id="studentsTab" class="tab-content">
            <div class="action-bar">
                <h3>参与学生</h3>
            </div>

            <div id="studentLoadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载学生列表...</p>
            </div>

            <div class="table-container">
                <table class="data-table" id="studentTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>学号</th>
                            <th>邮箱</th>
                            <th>考试状态</th>
                            <th>成绩</th>
                            <th>完成时间</th>
                        </tr>
                    </thead>
                    <tbody id="studentTableBody">
                        <!-- 学生数据将在这里动态生成 -->
                    </tbody>
                </table>
            </div>

            <div id="studentEmptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">👥</div>
                <h3 class="empty-title">暂无学生</h3>
                <p class="empty-description">这个考试还没有学生参与</p>
            </div>
        </div>

        <!-- 考试结果标签页 -->
        <div id="resultsTab" class="tab-content">
            <div class="action-bar">
                <h3>考试结果统计</h3>
            </div>

            <div class="table-container">
                <table class="data-table" id="resultTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>学号</th>
                            <th>答对题数</th>
                            <th>总题数</th>
                            <th>正确率</th>
                            <th>完成时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="resultTableBody">
                        <!-- 结果数据将在这里动态生成 -->
                    </tbody>
                </table>
            </div>

            <div id="resultEmptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">📊</div>
                <h3 class="empty-title">暂无结果</h3>
                <p class="empty-description">还没有学生完成这个考试</p>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentExam = null;
        let examQuestions = [];
        let examStudents = [];
        let examResults = [];
        let currentTab = 'overview';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExamData();
        });

        // 检查用户认证状态
        function checkAuth() {
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 0) {
                Message.error('请先登录管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            document.getElementById('userInfo').textContent = `欢迎，${user.name}`;
        }

        // 加载考试数据
        function loadExamData() {
            const urlParams = new URLSearchParams(window.location.search);
            const examId = urlParams.get('examId');
            
            if (!examId) {
                Message.error('考试ID不存在');
                setTimeout(() => {
                    window.location.href = 'exam-management.html';
                }, 1500);
                return;
            }

            loadExamInfo(examId);
            loadExamQuestions(examId);
            loadExamStudents(examId);
            loadExamResults(examId);
        }

        // 加载考试基本信息
        async function loadExamInfo(examId) {
            try {
                const response = await API.get(`/exam/${examId}`);
                if (response.success) {
                    currentExam = response.exam;
                    updateExamInfo();
                } else {
                    Message.error(response.message || '加载考试信息失败');
                }
            } catch (error) {
                console.error('加载考试信息失败:', error);
                Message.error('加载考试信息失败，请稍后重试');
            }
        }

        // 更新考试信息显示
        function updateExamInfo() {
            if (!currentExam) return;

            document.getElementById('examTitle').textContent = currentExam.title;
            document.getElementById('examDescription').textContent = currentExam.description || '查看考试详细信息和管理';
            document.getElementById('teacherName').textContent = currentExam.teacherName || '未知老师';
            document.getElementById('questionCount').textContent = `${currentExam.totalQuestions || 0} 题`;
            document.getElementById('timeLimit').textContent = `${currentExam.timeLimit || 0} 分钟`;
            document.getElementById('studentCount').textContent = `${currentExam.studentCount || 0} 人`;
            document.getElementById('createdTime').textContent = formatDate(currentExam.createdTime);
            document.getElementById('examStatus').textContent = getStatusText(currentExam.status);
            document.getElementById('examDescriptionText').textContent = currentExam.description || '暂无描述';

            // 更新操作按钮显示
            updateActionButtons();
        }

        // 更新操作按钮
        function updateActionButtons() {
            const publishBtn = document.getElementById('publishBtn');
            const unpublishBtn = document.getElementById('unpublishBtn');
            const endBtn = document.getElementById('endBtn');

            publishBtn.style.display = 'none';
            unpublishBtn.style.display = 'none';
            endBtn.style.display = 'none';

            switch (currentExam.status) {
                case 0: // 草稿
                    publishBtn.style.display = 'inline-block';
                    break;
                case 1: // 已发布
                    unpublishBtn.style.display = 'inline-block';
                    endBtn.style.display = 'inline-block';
                    break;
                case 2: // 已结束
                    // 不显示任何操作按钮
                    break;
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 0: return '草稿';
                case 1: return '已发布';
                case 2: return '已结束';
                default: return '未知';
            }
        }

        // 加载考试题目
        async function loadExamQuestions(examId) {
            try {
                const response = await API.get(`/exam/${examId}/questions`);
                if (response.success) {
                    examQuestions = response.questions || [];
                }
            } catch (error) {
                console.error('加载考试题目失败:', error);
            }
        }

        // 加载考试学生
        async function loadExamStudents(examId) {
            try {
                const response = await API.get(`/exam/${examId}/students`);
                if (response.success) {
                    examStudents = response.students || [];
                }
            } catch (error) {
                console.error('加载考试学生失败:', error);
            }
        }

        // 加载考试结果
        async function loadExamResults(examId) {
            try {
                const response = await API.get(`/exam/teacher/answers/${examId}`);
                if (response.success) {
                    examResults = response.records || [];
                    updateStats();
                }
            } catch (error) {
                console.error('加载考试结果失败:', error);
            }
        }

        // 更新统计信息
        function updateStats() {
            const totalParticipants = examStudents.length;
            const completedCount = examResults.length;
            const averageScore = completedCount > 0 ? 
                Math.round(examResults.reduce((sum, result) => sum + result.score, 0) / completedCount) : 0;
            const passRate = completedCount > 0 ? 
                Math.round((examResults.filter(result => result.score >= (currentExam.totalQuestions || 0) * 0.6).length / completedCount) * 100) : 0;

            document.getElementById('totalParticipants').textContent = totalParticipants;
            document.getElementById('completedCount').textContent = completedCount;
            document.getElementById('averageScore').textContent = averageScore;
            document.getElementById('passRate').textContent = `${passRate}%`;

            document.getElementById('statsGrid').style.display = 'grid';
        }

        // 切换标签页
        function switchTab(tabName) {
            // 更新标签页状态
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            event.target.classList.add('active');
            document.getElementById(tabName + 'Tab').classList.add('active');
            
            currentTab = tabName;
            
            // 根据标签页加载相应数据
            if (tabName === 'questions') {
                renderQuestionList();
            } else if (tabName === 'students') {
                renderStudentList();
            } else if (tabName === 'results') {
                renderResultList();
            }
        }

        // 渲染题目列表
        function renderQuestionList() {
            const questionList = document.getElementById('questionList');
            const loadingState = document.getElementById('questionLoadingState');
            const emptyState = document.getElementById('questionEmptyState');

            loadingState.style.display = 'none';

            if (examQuestions.length === 0) {
                showQuestionEmptyState();
                return;
            }

            questionList.innerHTML = examQuestions.map(eq => {
                const question = eq.question;
                if (!question) return '';

                return `
                    <div class="item-card">
                        <div class="item-header">
                            <h4 class="item-title">题目 #${question.id}</h4>
                            <div class="item-meta">
                                <span>${question.category || '未分类'}</span>
                                <span>${question.difficultyText || '未设置'}</span>
                            </div>
                        </div>
                        <div class="item-content">${question.content}</div>
                    </div>
                `;
            }).join('');

            questionList.style.display = 'grid';
        }

        // 渲染学生列表
        function renderStudentList() {
            const studentTable = document.getElementById('studentTable');
            const studentTableBody = document.getElementById('studentTableBody');
            const loadingState = document.getElementById('studentLoadingState');
            const emptyState = document.getElementById('studentEmptyState');

            loadingState.style.display = 'none';

            if (examStudents.length === 0) {
                showStudentEmptyState();
                return;
            }

            studentTableBody.innerHTML = examStudents.map(student => {
                const result = examResults.find(r => r.studentId === student.studentId);
                const status = result ? '已完成' : '未开始';
                const score = result ? `${result.score}/${result.totalQuestions}` : '-';
                const completedTime = result ? formatDate(result.examTime) : '-';

                return `
                    <tr>
                        <td>${student.studentName || '未知学生'}</td>
                        <td>${student.studentId}</td>
                        <td>${student.email || '-'}</td>
                        <td><span class="status-badge ${result ? 'status-published' : 'status-draft'}">${status}</span></td>
                        <td>${score}</td>
                        <td>${completedTime}</td>
                    </tr>
                `;
            }).join('');

            studentTable.style.display = 'table';
        }

        // 渲染结果列表
        function renderResultList() {
            const resultTable = document.getElementById('resultTable');
            const resultTableBody = document.getElementById('resultTableBody');
            const emptyState = document.getElementById('resultEmptyState');

            if (examResults.length === 0) {
                showResultEmptyState();
                return;
            }

            resultTableBody.innerHTML = examResults.map(result => {
                const student = examStudents.find(s => s.studentId === result.studentId);
                const percentage = result.totalQuestions > 0 ? 
                    Math.round((result.score / result.totalQuestions) * 100) : 0;

                return `
                    <tr>
                        <td>${student ? student.studentName : '未知学生'}</td>
                        <td>${result.studentId}</td>
                        <td>${result.score}</td>
                        <td>${result.totalQuestions}</td>
                        <td>${percentage}%</td>
                        <td>${formatDate(result.examTime)}</td>
                        <td>
                            <button class="btn-action btn-primary" onclick="viewStudentResult(${result.studentId})">
                                查看详情
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');

            resultTable.style.display = 'table';
        }

        // 显示题目空状态
        function showQuestionEmptyState() {
            document.getElementById('questionLoadingState').style.display = 'none';
            document.getElementById('questionList').style.display = 'none';
            document.getElementById('questionEmptyState').style.display = 'block';
        }

        // 显示学生空状态
        function showStudentEmptyState() {
            document.getElementById('studentLoadingState').style.display = 'none';
            document.getElementById('studentTable').style.display = 'none';
            document.getElementById('studentEmptyState').style.display = 'block';
        }

        // 显示结果空状态
        function showResultEmptyState() {
            document.getElementById('resultTable').style.display = 'none';
            document.getElementById('resultEmptyState').style.display = 'block';
        }

        // 发布考试
        async function publishExam() {
            if (!confirm('确定要发布这个考试吗？发布后学生就可以参加考试了。')) {
                return;
            }

            try {
                const response = await API.put(`/exam/admin/publish/${currentExam.id}`, {});
                if (response.success) {
                    Message.success('考试发布成功');
                    loadExamInfo(currentExam.id);
                } else {
                    Message.error(response.message || '发布失败');
                }
            } catch (error) {
                console.error('发布考试失败:', error);
                Message.error('发布失败，请稍后重试');
            }
        }

        // 取消发布考试
        async function unpublishExam() {
            if (!confirm('确定要取消发布这个考试吗？取消后学生将无法参加考试。')) {
                return;
            }

            try {
                const response = await API.put(`/exam/admin/unpublish/${currentExam.id}`, {});
                if (response.success) {
                    Message.success('考试取消发布成功');
                    loadExamInfo(currentExam.id);
                } else {
                    Message.error(response.message || '取消发布失败');
                }
            } catch (error) {
                console.error('取消发布考试失败:', error);
                Message.error('取消发布失败，请稍后重试');
            }
        }

        // 结束考试
        async function endExam() {
            if (!confirm('确定要结束这个考试吗？结束后将无法恢复。')) {
                return;
            }

            try {
                const response = await API.put(`/exam/end/${currentExam.id}`, {});
                if (response.success) {
                    Message.success('考试结束成功');
                    loadExamInfo(currentExam.id);
                } else {
                    Message.error(response.message || '结束考试失败');
                }
            } catch (error) {
                console.error('结束考试失败:', error);
                Message.error('结束考试失败，请稍后重试');
            }
        }

        // 查看考试结果
        function viewExamResults() {
            window.open(`exam-results.html?examId=${currentExam.id}`, '_blank');
        }

        // 查看学生结果
        function viewStudentResult(studentId) {
            window.open(`student-result.html?examId=${currentExam.id}&studentId=${studentId}`, '_blank');
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                UserManager.logout();
                window.location.href = '../login.html';
            }
        }
    </script>
</body>
</html>
